﻿using MediatR;
using Traceability.App.API.Application.Command.BasicTraceability;
using Traceability.App.API.DTOs;
using Traceability.App.Domain.Traceability;
using Traceability.App.ErrorCode;
using Traceability.App.Infrastructrue.Interface;

namespace Traceability.App.API.Application.Handler.BasicTraceability
{
    public class GetBasicTraceabilityHandler : IRequestHandler<GetBasicTraceabilityCommand, APIPaging<BasicTraceabilityDTO>>
    {
        private readonly IBaseRepository<BasicTraceabilityModel> basicRepo;
        private readonly IBaseRepository<GoodModel> goodRepo;

        public GetBasicTraceabilityHandler(IBaseRepository<BasicTraceabilityModel> basicRepo,
                                           IBaseRepository<GoodModel> goodRepo)
        {
            this.basicRepo = basicRepo;
            this.goodRepo = goodRepo;
        }
        public Task<APIPaging<BasicTraceabilityDTO>> Handle(GetBasicTraceabilityCommand request, CancellationToken cancellationToken)
        {
            APIPaging<BasicTraceabilityDTO> result = new APIPaging<BasicTraceabilityDTO>();
            var basic = basicRepo.GetAll().Where(x => !x.IsDel).ToList();
            var good = goodRepo.GetAll().Where(x => !x.IsDel).ToList();
            var query = from a in basic
                        join b in good on a.GoodId equals b.Id
                        select new BasicTraceabilityDTO
                        {
                            Id = a.Id,
                            Batch = a.Batch,
                            CoverImg = a.CoverImg,
                            GoodId = a.GoodId,
                            GoodName = b.GoodName,
                            Information = a.Information,
                            Manufacturer = a.Manufacturer,
                            PLNumber = a.PLNumber,
                            QGPeriod = a.QGPeriod,
                            CreateDate = a.CreateDate,
                            CreateName = a.CreateName,
                            UpdateDate = a.UpdateDate,
                            UpdateName = a.UpdateName
                        };
            result.TotalCount = query.Count();
            result.TotalPage = (int)Math.Ceiling(result.TotalCount * 1.0 / request.PageSize);
            result.PageDatas = query.OrderByDescending(x => x.CreateDate).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            return Task.FromResult(result);
        }
    }
}
